package cn.hy.dataSync.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;


import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

public class TraceIdUtil {
    private static Logger logger = LoggerFactory.getLogger(TraceIdUtil.class);
    public static final String TRACE_ID_KEY = "traceId";
    public static final String REQ_ID_KEY = "requestId";
    private static ThreadLocal<String> traceIdThreadLocal = new TransmittableThreadLocal();

    public TraceIdUtil() {
    }

    public static void initTraceId(HttpServletRequest request) {
        try {
            String contextTraceId = request.getHeader("requestId");
            if (StringUtils.isEmpty(contextTraceId)) {
                contextTraceId = createTraceId();
                request.setAttribute("requestId", contextTraceId);
            }

            traceIdThreadLocal.set(contextTraceId);
            MDC.put("traceId", contextTraceId);
        } catch (Exception var2) {
            logger.warn("Oops, Something bad happened. {}", Throwables.getStackTraceAsString(var2));
        }

    }

    public static void initTraceId() {
        String contextTraceId = getCurrentTraceId();
        if (StringUtils.isEmpty(contextTraceId)) {
            contextTraceId = createTraceId();
            traceIdThreadLocal.set(contextTraceId);
        }

        MDC.put("traceId", contextTraceId);
    }

    public static void initTraceId(String traceId) {
        if (!StringUtils.isEmpty(traceId)) {
            setCurrentTraceId(traceId);
            MDC.put("traceId", traceId);
        }

    }

    public static void clearTraceId() {
        traceIdThreadLocal.remove();
        MDC.remove("traceId");
    }

    private static String createTraceId() {
        String id = UUID.randomUUID().toString().toLowerCase().replace("-", "");
        return id;
    }

    public static String getCurrentTraceId() {
        return (String)traceIdThreadLocal.get();
    }

    private static void setCurrentTraceId(String traceId) {
        traceIdThreadLocal.set(traceId);
    }
}
